﻿using FirstFloor.ModernUI.Presentation;
using FirstFloor.ModernUI.Windows.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Microsoft.Practices.Unity;
using appCtx = EasyInvoice.ApplicationContext.AppContext;

namespace EasyInvoice.WPF.ViewModel
{
    public class UserListViewModel : NotifyPropertyChanged
    {
        
        private string _name = string.Empty;

        public string Name
        {
            get
            {
                return this._name;
            }
            set
            {
                this._name = value;
                this.OnPropertyChanged("Name");
            }
        }
        
        private Services.UsersService _serviceUsers;

        public Uri SelectedLink { get; set; }

        public LinkCollection UserLinks
        {
            get 
            {
                return new LinkCollection(from UserViewModel user in GetUsers()
                                          select new Link()
                                          {
                                              DisplayName = user.UserName,
                                              Source = new Uri(user.Id.ToString(), UriKind.Relative)
                                          }
                            );
            }
        }

        private ObservableCollection<UserViewModel> GetUsers()
        {
            var returnValue = new ObservableCollection<UserViewModel>();
            var dbusers = this._serviceUsers.GetAll();
            dbusers = from Model.User u in dbusers
                    where u.UserName.ToUpperInvariant().Contains(_name.ToUpperInvariant())
                    select u;
            dbusers.ToList().ForEach(user => returnValue.Add(new UserViewModel(user)));
            return returnValue;
        }

        public UserListViewModel()
        {
            _serviceUsers = appCtx.Instance.IoC.Resolve<Services.UsersService>();
        }

        //private  void SetLinks()
        //{
        //  foreach (UserViewModel user in GetUsers())
        //    {
        //        try
        //        {
        //            Link link = new Link();
        //            link.DisplayName = user.UserName;
        //            Uri uri = new Uri(user.Id.ToString(), UriKind.Relative);
        //            link.Source = uri;
        //            userLinks.Add(link);
        //        }
        //        catch (Exception ex)
        //        {
        //            throw ex;
        //        }
        //    }
        //}


        private ICommand showAddCommand;

        public ICommand ShowAddCommand
        {
            get
            {
                if (showAddCommand == null)
                {
                    showAddCommand = new Common.CommandBase(
                        i => this.AddUser(),
                        i => ((UserViewModel)Properties.Settings.Default.AuthenticatedUser) != null ? ((UserViewModel)Properties.Settings.Default.AuthenticatedUser).AddUsers : false);
                }
                return showAddCommand;
            }
        }

        private void AddUser()
        {
            SelectedLink = new Uri(string.Format("0|{0}", DateTime.Now.Ticks), UriKind.Relative);
            this.OnPropertyChanged("SelectedLink");
        }

        //for opening up the Delete User window
        private ICommand showDeleteCommand;

        public ICommand ShowDeleteCommand
        {
            get
            {
                if (showDeleteCommand == null)
                {
                    showDeleteCommand = new Common.CommandBase(
                        i => this.DeleteUser(),
                        i => this.CanDelete());
                }
                return showDeleteCommand;
            }
        }

        private void DeleteUser()
        {
            //UserViewModel user = new UserViewModel(new ModelCE.User().GetByIDCE(Convert.ToInt32(SelectedLink.ToString())));
            UserViewModel user = new UserViewModel( _serviceUsers.Get(Convert.ToInt32(SelectedLink.ToString())));
            var result = ModernDialog.ShowMessage(string.Format("Do you want to delete user {0} ?", user.UserName), "Delete User Dialog", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    user.Delete();
                    SelectedLink = UserLinks.First().Source;
                }
                catch (Exception ex)
                {
                    ModernDialog.ShowMessage(ex.Message, "Delete User Failed", MessageBoxButton.OK);
                }
            }
            this.OnPropertyChanged("UserLinks");
            this.OnPropertyChanged("SelectedLink");

        }

        private bool CanDelete()
        {
            if (object.Equals((UserViewModel)Properties.Settings.Default.AuthenticatedUser, null)) return false;
            if (object.Equals(SelectedLink, null)) return false;
            var authUser = (UserViewModel)Properties.Settings.Default.AuthenticatedUser;
            long userId = 0;
            if (!SelectedLink.OriginalString.Contains("|")) userId = Convert.ToInt32(SelectedLink.OriginalString);
            var selectedUser = new UserViewModel( this._serviceUsers.Get(userId));

            if (authUser.Id == selectedUser.Id) return false;
            if (selectedUser.PreventEditOrDelete) return selectedUser.PreventEdit;

            return authUser.DeleteUsers;
        }

        private ICommand refreshCommand;

        public ICommand RefreshCommand
        {
            get
            {
                if (refreshCommand == null)
                {
                    refreshCommand = new Common.CommandBase(i => this.RefreshUsers(), null);
                }
                return refreshCommand;
            }
        }

        private void RefreshUsers()
        {
            //save user
            this.OnPropertyChanged("UserLinks"); 
        }
    }
}
